#!/bin/bash

tarfile=SelCode.tgz 
#athenaTag="17.2.1"
athenaTag="17.0.5"
rootTag="5.28.00"

output="skim_tree.root,skim_histo.root,log_eff_ee_physics.txt,log_eff_em_physics.txt,log_eff_mm_physics.txt,log_eff_incl_physics.txt,log_eff_obj_physics.txt,log_run.txt,input_list.txt,output_log.txt"

print_help() {   #use -h or --help option to print help
  cat <<EOF
   prun.sh [-s] [-t] <dataset or list of datasets>
    -t => test, just print prun command
    -x => Submit as express job, for testing
    -s => Do list of datasets in list of datasets as single big job
          default is to do each dataset separately
    <dataset or list of datasets> = Either a single dataset or a file 
      with a list of datasets, one per line.  File must have .txt filename extension.
      datasets are assumed to end in "/".  A "/" is added if needed.
    This is customized for Lepton-Jet skim job submission:
     1. Naming scheme for output datasets
     2. Specific parameters passed to prun command
EOF
}
##############################################################
#  prun command
##############################################################
#  --individualOutDS \
submit() {
  pruncmd="prun $opts $inDS 
    --outDS=${outDS} 
    --nGBPerJob=10 
    --athenaTag=$athenaTag 
    --inTarBall=$tarfile 
    --bexec='./run_make.sh' 
    --exec='python run_ana.py %IN' 
    --outputs *.root,log_eff*.txt"
  if [[ $test -eq 1 ]]; then
    echo $pruncmd
    exit
  fi
  if [ ! -d log ]; then mkdir log; fi
  if [ ! -d history ]; then mkdir "history"; fi
  log=log/$outDS.log
  echo "##### `date`:  Submit job for ${dset}"
  echo "##### `date`:  Submit job for ${dset}" > ${log}
  echo $pruncmd >> ${log} 2>&1
### this does not work (issues with keeping the quotes straight)
#  ${pruncmd} >> ${log} 2>&1
### Here is the actual prun submission command   
# data stream type
  input_type="MC"
  if [[ "${inDS}" == *Egamma* ]]; then input_type="Egamma"
  elif [[ "${inDS}" == *Muons* ]]; then input_type="Muons"
  fi 
  prun $opts $inDS --outDS=${outDS} --nGBPerJob=10 --athenaTag=$athenaTag --rootVer=$rootTag --inTarBall=$tarfile --bexec="./run_make.sh" --exec="python run_ana.py %IN ${input_type}" --outputs=$output >> ${log} 2>&1
  #prun $opts $inDS --outDS=${outDS} --nGBPerJob=10 --athenaTag=$athenaTag --inTarBall=$tarfile --bexec="./run_make.sh" --exec="python run_ana.py %IN ${input_type}" --outputs=$output --excludedSite=ANALY_INFN-ROMA1 >& out_failed
  #prun $opts $inDS --outDS=${outDS} --nGBPerJob=10 --athenaTag=$athenaTag --inTarBall=$tarfile --bexec="./run_make.sh" --exec="python run_ana.py %IN ${input_type}" --outputs=$output >& out_failed
### Check if it worked
  if [ $? -eq 0 ]; then
    jobid=`grep JobID $log | awk '{print $3}'`
    njobs=`grep submit $log | awk '{print $4}'`
    echo "$jobid $outDS $njobs" >> "history"/${date}_${name}_log.txt
    echo "  Submitted JobID $jobid ${outDS}/ $njobs jobs"
  else
    echo "  Submission failed $outDS"
    echo "0 $outDS FAIL" >> "history"/${date}_${name}_log.txt
    rm ${log}
  fi
}
##############################################################
#  do single dataset
##############################################################
single() {
# remove / from end if present
  ddset=`echo $dset | sed 's/\///g'`
  outDS=user.lxu.output.$datehm.$ddset
  # prun requires the outDS length no more than 132
  len=`echo $outDS | wc -m`
  if [ $len -gt 132 ]; then 
    new_outDS=${outDS//_/}
    outDS=$new_outDS
    len=`echo $outDS | wc -m`
    if [ $len -gt 132 ]; then
       new_outDS=${outDS:0:131}
       outDS=$new_outDS
    fi
  fi
  
#  name=$ddset
  if [[ "${ddset}" == *"tid"* ]]; then
    inDS="--inDS=${ddset}"
  else
    inDS="--inDS=${ddset}/"
  fi
  submit
}
##############################################################
#  MAIN
##############################################################
#  Parse options
while [ $# -ne 0 ]; do
  if [[ "$1" == "-h" || "$1" == "--help" ]]; then
    print_help; exit
  elif [[ $1 == "-s" ]]; then
    all=1
  elif [[ $1 == "-t" ]]; then
    test=1
  elif [[ $1 == "-x" ]]; then
    opts="--express"
  elif [[ $list == "" ]]; then
    list=$1
  fi
  shift 1
done
date=`date +%Y%m%d`
datehm=`date +%Y%m%d%H%M`
###  If doing a list of datasets
if [[ -e $list ]]; then
  name=`basename $list`
  if [[ $all -eq 1 ]]; then
    inDS="--inDsTxt=$list"
    outDS=user.lxu.$datehm.${name}
    dset=$list
    submit
  else
    while read d1 d2 junk; do
#  If d1 is a number then the dataset is d2
      if echo $d1 | grep '^[-|+|0-9|.][.0-9]*$' &> /dev/null ; then
        dset=$d2
      elif [[ "$d1" != *"#"* ]]; then
        dset=$d1
      fi
      echo "INFO => To submit job with dataset: $dset"
      single
    done <$list
  fi
### Else single dataset 
else  
  name=single 
  dset=$list
  single
fi
